<template>
	<div>
		<use-table ref="tbl"></use-table>
		<div ref="advanced" class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">导航名称：</div>
					<el-input v-model="req.name" placeholder="请输入" @change="search" class="search_input" clearable>
					</el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">跳转地址：</div>
					<el-input v-model="req.url" placeholder="请输入" @change="search" class="search_input" clearable>
					</el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">跳转类型：</div>
					<el-select v-model="req.type" class="search_input" @change="search" clearable>
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">状态：</div>
					<el-select v-model="req.state" class="search_input" @change="search" clearable>
						<el-option v-for="item in stateOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedFilter" v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedFilter" v-if="advancedSearch">常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<div class="dflex_vertical_c">
					<el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes">删除<span
							v-if="selectDatas.length">×{{selectDatas.length}}</span></el-button>
					<el-radio-group @change="classifyNumChange" class="margin_l_30" v-model="classifyNum">
						<!-- <el-tooltip :open-delay="350" content="设置前端金刚区布局3个为一列" placement="top" :enterable="false"
							effect="light">
							<el-radio-button :label="3"></el-radio-button>
						</el-tooltip> -->
						<el-tooltip :open-delay="350" content="设置前端金刚区布局4个为一列" placement="top" :enterable="false"
							effect="light">
							<el-radio-button :label="4"></el-radio-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" content="设置前端金刚区布局5个为一列" placement="top" :enterable="false"
							effect="light">
							<el-radio-button :label="5"></el-radio-button>
						</el-tooltip>
					</el-radio-group>
					<div class="remark_txt el-icon-info margin_t_0 margin_l_15 h_initial">设置前端分类导航布局</div>
				</div>
				<el-button class="add-btn pos_r padding0" icon="iconfont iconxinzeng" @click="toAdd">新增</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas"
				@selection-change="selectionChange" highlight-current-row>
				<el-table-column type="selection"></el-table-column>
				<el-table-column label="排序" width="200" align="center">
					<template slot-scope="scope">
						<el-input-number size="small" :min="1" v-model="scope.row.sort"
							@change="(newSort, oldSort) => sortChange(newSort, oldSort, scope.row)"
							@blur="scope.row.sort = parseInt(scope.row.sort)"></el-input-number>
					</template>
				</el-table-column>
				<el-table-column property="name" label="导航名称" align="center"></el-table-column>
				<el-table-column label="分类图片" align="center">
					<template slot-scope="scope">
						<el-image class="headimg" :src="scope.row.img" :preview-src-list="scope.row.previewImgs"
							fit="contain"></el-image>
					</template>
				</el-table-column>
				<el-table-column property="type" label="跳转类型" align="center"></el-table-column>
				<el-table-column property="url" label="跳转地址" width="250" align="center"></el-table-column>
				<el-table-column property="state" label="状态" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" :content="scope.row.state == '启用' ? '点击禁用' : '点击启用'"
							placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-switch v-model="scope.row.state" active-color="#ff6a6c" inactive-color="#bbb"
								active-value="启用" inactive-value="禁用" @change="stateChange(scope.row)"></el-switch>
						</el-tooltip>
					</template>
				</el-table-column>
				<el-table-column label="备注" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.remark || '--' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" content="编辑" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-edit" class="table-btn"
								@click="toEdit(scope.row._id)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" content="删除" placement="top" :hide-after="1000" :enterable="false"
							effect="light">
							<el-button circle size="medium" icon="el-icon-delete" class="table-btn"
								@click="remove(scope.row._id)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
	</div>
</template>

<script>
	const __name = 'wmzmall-app-category';
	const __appParameter = 'wmzmall-app-parameter';
	export default {
		data() {
			return {
				diff: 0,
				advancedHeight: 0,
				advancedSearch: false,
				typeOptions: [{
						value: '',
						label: '全部'
					},
					{
						value: '网页',
						label: '网页'
					},
					{
						value: '页面',
						label: '页面'
					}
				],
				stateOptions: [{
						value: '',
						label: '全部'
					},
					{
						value: '启用',
						label: '启用'
					},
					{
						value: '禁用',
						label: '禁用'
					}
				],
				req: {
					page: 1,
					rows: 10,
					orderby: 'sort asc',
					name: '',
					url: '',
					type: '',
					state: ''
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				selectDatas: [],
				searchBtnLoading: false,
				removesBtnLoading: false,
				classifyNum: 0,
				classifyNumPrev: 0,
				sortLastTime: null
			};
		},
		methods: {
			async loadData(callback) {
				this.tableLoading = true;

				await this.$db[__appParameter].tofirst({
					loading: false
				}).then(res => {
					if (res.code == 200) {
						res.datas = res.datas || {};
						this.classifyNum = res.datas.classify_num || 4;
						this.classifyNumPrev = res.datas.classify_num || 4;
					}
				});

				await this.$db[__name]
					.whereif(this.req.name, {
						name: new RegExp(this.$api.filterRegexpKey(this.req.name), 'i')
					})
					.whereif(this.req.url, {
						url: new RegExp(this.$api.filterRegexpKey(this.req.url), 'i')
					})
					.whereif(this.req.type, {
						type: this.req.type
					})
					.whereif(this.req.state, {
						state: this.req.state
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							res.datas.rows.forEach((row, idx) => {
								row.previewImgs = [row.img];
							});

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			toAdd() {
				uni.navigateTo({
					url: `/pages/shop/classify/classify_navigation_add_edit?tab=添加分类`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			toEdit(id) {
				uni.navigateTo({
					url: `/pages/shop/classify/classify_navigation_add_edit?id=${id}&tab=编辑分类`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			remove(id) {
				this.$confirm('此操作将永久删除该数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].remove(id).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
					});
				});
			},
			selectionChange(datas) {
				this.selectDatas = datas;
			},
			removes() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要删除的数据');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将永久删除勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removesBtnLoading = true;
					this.$db[__name]
						.where({
							_id: this.$db.$cmd.in(ids)
						})
						.remove()
						.then(res => {
							if (res.code == 200) {
								this.loadData();
							}
							this.removesBtnLoading = false;
						}).catch(() => {
							this.removesBtnLoading = false;
						})
				});
			},
			sortChange(newSort, oldSort, row) {
				if (!newSort) {
					this.$nextTick(() => {
						row.sort = oldSort;
					})
					return;
				}

				if (event && ['change', 'mouseup'].includes(event.type)) {
					this.sortUpdate(row);
					return;
				}

				if (this.sortLastTime !== null) {
					clearTimeout(this.sortLastTime)
				}

				this.sortLastTime = setTimeout(() => {
					this.sortUpdate(row)
				}, 500);
			},
			sortUpdate(row) {
				this.$db[__name].update(row._id, {
					sort: parseInt(row.sort)
				}).catch(() => {
					this.loadData();
				})
			},
			stateChange(row) {
				this.$db[__name].update(row._id, {
					state: row.state
				}).catch(() => {
					this.loadData();
				})
			},
			advancedFilter() {
				this.advancedSearch = !this.advancedSearch;

				this.$nextTick(() => {
					if (this.advancedSearch) {
						this.diff = this.$refs.advanced.clientHeight - this.advancedHeight;
					}
					this.$refs.tbl.tableInit(this.advancedSearch ? -this.diff : this.diff);
					this.$refs.tbl.tableChange();
				});
			},
			classifyNumChange(res) {
				this.$confirm(`此操作将设置前端金刚区布局${res}个为一列！`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.classifyNumPrev = res;
						this.$func.wmzadmin
							.call('app/parameter', {
								classify_num: res,
								shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
							})
							.then(res => {
								if (res.code == 200) {
									this.$message({
										message: res.datas,
										type: 'success'
									});
									return;
								}
								this.loadData();
							})
					})
					.catch(() => {
						this.classifyNum = this.classifyNumPrev;
					});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.type || this.req.state) {
					this.advancedSearch = true;
				}
			}

			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.advancedHeight = this.$refs.advanced.clientHeight;

			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	>>>.el-radio-group {
		height: 40px;
	}

	>>>.el-radio-button:not(.is-active) .el-radio-button__inner:hover {
		color: #7e6aff !important;
	}

	>>>.el-radio-button__orig-radio:checked+.el-radio-button__inner {
		background-color: #7e6aff;
		border-color: #7e6aff;
		box-shadow: -1px 0 0 0 #7e6aff;
	}

	>>>.el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
		box-shadow: initial;
	}
</style>
